package com.kexilo.logging.aspect;

import com.alibaba.fastjson2.JSON;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.security.UserPrincipal;
import com.kexilo.core.common.utils.*;
import com.kexilo.logging.service.LoggingService;
import com.kexilo.logging.domain.LogRecord;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理 - logging插件版本
 * 作为logging插件的一部分，提供AOP日志记录功能
 * 
 * @author Kexilo
 */
@Aspect
public class LogAspect {
    
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    
    /** 排除敏感属性字段 */
    public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
    
    @Autowired
    private LoggingService loggingService;
    
    /** 处理完请求后执行 */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /** 拦截异常操作 */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前的用户
            UserPrincipal loginUser = SecurityUtils.getLoginUser();

            // 请求的地址
            String ip = IpUtils.getIpAddr();
            HttpServletRequest request = ServletUtils.getRequest();
            
            // 构建操作日志记录 - 使用logging插件的LogRecord
            LogRecord.Builder builder = LogRecord.builder()
                    .type(LogRecord.LogType.OPERATION)
                    .level(e == null ? LogRecord.LogLevel.INFO : LogRecord.LogLevel.ERROR)
                    .ip(ip)
                    .operLocation(IpUtils.getRealAddressByIP(ip))
                    .url(StringUtils.substring(request.getRequestURI(), 0, 255))
                    .operTime(LocalDateTime.now())
                    .userAgent(request.getHeader("User-Agent"))
                    .traceId(MDC.get("traceId"))
                    .status(e == null ? HttpStatus.OK.value() : HttpStatus.INTERNAL_SERVER_ERROR.value());

            if (loginUser != null) {
                builder.username(loginUser.getUsername());
                // TODO: 可以在未来添加部门和租户信息
                // builder.extra("deptName", loginUser.getDeptName())
                //        .extra("tenantId", loginUser.getTenantId());
            }

            if (e != null) {
                builder.errorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            builder.className(className)
                   .methodName(methodName)
                   .method(request.getMethod());
            
            // 设置消耗时间
            Long startTime = (Long) request.getAttribute("startTime");
            if (startTime != null) {
                builder.costTime(System.currentTimeMillis() - startTime);
            }
            
            // 设置请求大小（暂时存储在browser字段中，将来可以扩展LogRecord）
            String requestBody = ServletUtils.getBodyString(request);
            if (StringUtils.isNotEmpty(requestBody)) {
                builder.browser("RequestSize:" + requestBody.getBytes().length);
            }
            
            LogRecord operLog = builder.build();
            
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            
            // 使用logging插件记录日志 - 完全解耦的插件化架构
            loggingService.log(operLog);
            
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("操作日志记录异常：{}", exp.getMessage(), exp);
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * 
     * @param joinPoint 切点
     * @param log 日志注解
     * @param operLog 操作日志记录
     * @param jsonResult 返回结果
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, LogRecord operLog, Object jsonResult) throws Exception {
        // 设置业务类型和标题（暂时存储在os字段中，将来可以扩展LogRecord）
        operLog.setOs("BusinessType:" + log.businessType().ordinal());
        operLog.setTitle(log.title());
        
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog, log.excludeParamNames());
        }
        
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
            operLog.setResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
        }
    }

    /**
     * 获取请求的参数，放到log中
     * 
     * @param joinPoint 切点
     * @param operLog 操作日志记录
     * @param excludeParamNames 排除的参数名
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, LogRecord operLog, String[] excludeParamNames) throws Exception {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (map != null && !map.isEmpty()) {
            String params = JSON.toJSONString(map, excludePropertyFilter(excludeParamNames));
            operLog.setParams(StringUtils.substring(params, 0, 2000));
        } else {
            Object args = joinPoint.getArgs();
            if (StringUtils.isNotNull(args)) {
                String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);
                operLog.setParams(StringUtils.substring(params, 0, 2000));
            }
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o, excludePropertyFilter(excludeParamNames));
                        params.append(jsonObj).append(" ");
                    } catch (Exception e) {
                        // 处理序列化异常
                        params.append(o.toString()).append(" ");
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 忽略敏感属性的过滤器
     */
    private com.alibaba.fastjson2.filter.PropertyFilter excludePropertyFilter(String[] excludeParamNames) {
        String[] allExcludes = ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames);
        return (object, name, value) -> {
            for (String exclude : allExcludes) {
                if (exclude.equals(name)) {
                    return false;
                }
            }
            return true;
        };
    }

    /**
     * 判断是否需要过滤的对象。
     * 
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
